import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import LoginVue from "../views/login/index.vue";
import { userInfoAPI } from "@/http/api/index";
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: LoginVue,
  },
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/",
    component: () => import("../views/home/index.vue"),
    children: [
      {
        path: "index",
        component: () => import("../views/index/index.vue"),
      },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  const store = useUserStore();
  let token = localStorage.getItem("token");
  //因为每个页面都需要进行权限的验证，所以在这里面判断菜单数据有了没有，如果没有，我们需要发请求，来动态获取菜单数据
  // 有token，没有数据时才请求菜单
  if (store.menus.length === 0 && token) {
    // 我们会把请求成功后的菜单数据放在pinia里面
    userInfoAPI().then((res) => {
      if (res.code === 200) {
        // 把数据存到pinia
        // pinia  里面可以直接修改数据
        store.menus = res.data.menus;
        // 存储用户名
        store.username = res.data.username;
        store.routes.forEach((p) => {
          const route: RouteRecordRaw = {
            path: "/" + p.name,
            name: p.name,
            component: () => import("../views/home/index.vue"),
            meta: {
              title: p.title,
            },
            children: p.children.map((item) => ({
              path: item.name,
              name: item.name,
              component: () => import(`../views/${p.name}/${item.name}.vue`),
              meta: {
                title: item.title,
              },
            })),
          };
          if (p.children[0]) {
            route.redirect = `/${p.name}/${p.children[0]?.name}`;
          }
          // 路由里面提供了一个方法，用来动态添加路由的
          router.addRoute(route);
        });
        next(to.fullPath);
      }
    });
  }
  // 判断有无token，如果没有token，并且访问的不是login 就跳转回 login
  else if (!token && to.path !== "/login") {
    ElMessage.error("请先登录");
    next("/login");
  }
  // 如果用户在登录的时候，不让用户通过手动跳转倒登录页面
  else if (token && store.menus.length !== 0 && to.path === "/login") {
    ElMessage.warning("请先退出用户后再重新登陆！");
    // 让它从哪里来回哪里去
    next(from.fullPath);
  } else {
    next();
  }
});

export default router;
